package com.itheima.htmo_01.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.htmo_01.pojo.AvatarImage;
import com.itheima.htmo_01.pojo.Result;
import com.itheima.htmo_01.service.AvatarImageService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


@CrossOrigin(origins = "*")
@RestController
public class FileController {

    @Resource
    private AvatarImageService avatarImageService;

    @PostMapping("/upload")
    public Result<Integer> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {



        // 获取用户上传的图片名称
        String name = file.getOriginalFilename();
        String[] split = name.split("\\.");
        // 获取图片的类型
        String fileType = split[split.length-1];

        String fileName = IdUtil.getSnowflakeNextId() + "." +fileType;

        File path = new File("D:"+ File.separator + "data");
        if(!path.exists()){
            path.mkdirs();
        }

        File temp = new File(path.getAbsoluteFile() + File.separator  + fileName);


        file.transferTo(temp);

        AvatarImage avatarImage = new AvatarImage();
        avatarImage.setPath(temp.getAbsolutePath());
        avatarImage.setFileName(fileName);
        avatarImage.setFileType(fileType);
        avatarImageService.save(avatarImage);

        return Result.success(avatarImage.getId());
    }

    @GetMapping("/download/{id}")
    public void downloadFile(@PathVariable String id, HttpServletResponse response) throws IOException {

        AvatarImage avatarImage = avatarImageService.getById(id);

        if(ObjectUtil.isEmpty(avatarImage)){
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }

        // 获取要下载的文件路径
        String filePath = avatarImage.getPath(); // 修改为实际文件存储路径

        // 创建文件对象
        File file = new File(filePath);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        // 设置响应头，允许在线浏览图片
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + avatarImage.getFileName() + "\"");

        // 设置响应内容类型为文件流
        MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
        if (avatarImage.getFileType().equals("png")) {
            mediaType = MediaType.IMAGE_PNG;
        } else if (avatarImage.getFileType().equals("jpg")) {
            mediaType = MediaType.IMAGE_JPEG;
        }
        headers.setContentType(MediaType.IMAGE_PNG);

        // 读取文件并输出到响应流
        FileInputStream inputStream = new FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();

        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        inputStream.close();
        outputStream.flush();
        outputStream.close();

    }


}
